<?php
/* capturer.php
 * ------------
 * Convierte la informacion de los logs de las llamadas
 * a JSON, que es el formato utilizado por la libreria
 * que arma el grafico en flash.
 * -----------------------------------------------------
 * Gustavo Borgoni - gborgoni@gmail.com
 */

error_reporting(0);

include 'lib/php/open-flash-chart.php';
include 'lib/config.php';

/* get_calls
 * ---------
 * Trae la informacion de llamadas concurrentes que
 * estan guardadas en el archivo de log, y devuelve
 * un array con las mediciones.
 */
function get_calls() {
	global $cache_dir, $month, $day, $year, $diff;

	$log = array();
	$i   = 0;

	$fp = fopen("$cache_dir/calls.log",'r');
	if ($fp) {
		while (!feof($fp)) {
			$data = fgets($fp, 4096);
			list($lines, $date) = explode(",",$data);

			if (is_numeric($lines)) {
				$logday  = str_replace("-", "", substr(trim($date),0,10));
				
				$day   = substr(trim($date),8,2);
				$month = substr(trim($date),5,2);
				$year  = substr(trim($date),0,4);

				$hour  = substr(trim($date),11,2);
				$min   = substr(trim($date),14,2);

				$k = mktime($hour, $min, 0, $month, $day, $year)-$diff;
				if ($log[$k] == 0 || $log[$k] == "") {
					$log[$k] = $log[$k] + $lines;
				} else {
					$log[$k] = round(($log[$k] + $lines) / 2);
				}
			}
		}
		fclose($fp);

		return $log;
	}

	return null;
}

$log = get_calls();

if (!is_null($log)) {
	$max_calls    = max($log);
	$max_y_values = $max_calls + round((15 * $max_calls) / 100);
} else {
	$title = "No se pudo obtener el registro de llamados";
}

if ($max_y_values == 0) {
	$max_y_values = 100;
}

foreach ($log as $k => $v) {
	$vals[] = new scatter_value($k,$v);
}

/* Titulo del grafico */
$chart_title = new title($title);
$chart       = new open_flash_chart();

$chart->set_title( $chart_title );

$line = new line();
$line->set_values($vals);
$line->set_colour('#8084FF');
$line->set_width(3);

/* Valores del eje X */
$x = new x_axis();
$x->set_range(
		mktime(0, 0, 0, $month, $day, $year)-$diff,
		mktime(23, 59, 59, $month, $day, $year)-$diff);
$x->set_steps(1800);
$x->set_colours("#999999", "#EFEFEF");

$x_lab = new x_axis_labels();
$x_lab->text('#date: H:i#');
$x_lab->set_steps(1800);
$x_lab->visible_steps(2);
$x_lab->set_vertical();

$x->set_labels( $x_lab );

/* Valores del eje Y */
$y = new y_axis();
$y->set_range( 0, $max_y_values , round($max_y_values / 5)); 
$y->set_colours("#999999", "#EFEFEF");

/* Parametros generales */
$chart->set_bg_colour( '#FFFFFF' );
$chart->set_y_axis( $y );
$chart->set_x_axis( $x );
$chart->add_element($line);

/* Devuelve el JSON */
echo $chart->toPrettyString();
?>
